const Router = require('koa-router')
const _ = require('lodash')
const { error, INFO } = require('./utils/error')
const {
  requestAllClass,
  requestUserClass,
  requestEditUserClass
} = require('./api/classification')
const router = new Router({
  prefix: '/api/classification'
})
const apiError = (info) => {
  error('50000', __filename, info)
}
router.get('/allClass', async (ctx) => {
  let result = []
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestAllClass()
    if (status === 200 && data.statu === 0) {
      code = 1
      result = data.data.map((item) => {
        return {
          id: item.id,
          name: item.name,
          map: item.class.map((itemMap) => {
            return {
              id: itemMap.id,
              name: itemMap.name
            }
          })
        }
      })
    }
  } catch {
    apiError('GET-allClass')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})

router.get('/userClass', async (ctx) => {
  let result = []
  let code = -1
  let msg = ''
  try {
    if (ctx.isAuthenticated()) {
      const { status, data } = await requestUserClass({
        id: ctx.session.passport.user.id
      })
      if (status === 200 && data.statu === 0) {
        code = 1
        if (_.isEmpty(data.data) || data.data === '[]') {
          code = 0
        } else {
          code = 1
          result = JSON.parse(data.data).map((item) => {
            return {
              id: item.id,
              name: item.name
            }
          })
        }
      }
    } else {
      code = -1
      msg = '用户未登陆'
    }
  } catch {
    apiError('GET-userClass')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})
router.post('/userClass', async (ctx) => {
  const body = ctx.request.body
  let code = -1
  let msg = ''
  try {
    if (ctx.isAuthenticated()) {
      const { status, data } = await requestEditUserClass({
        id: ctx.session.passport.user.id,
        value: JSON.stringify(body.userClass)
      })
      if (status === 200 && data.statu === 0) {
        code = 0
      }
    } else {
      code = -1
      msg = '用户未登陆'
    }
  } catch {
    apiError('POST-userClass')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      msg
    }
  }
})
module.exports = router
